Better Stack JavaScript client: Helper tools
📣 Logtail is now part of Better Stack. Learn more ⇗
Looking for a logging solution?
Check out Better Stack and Better Stack clients for JavaScript and Node.js.
@logtail/tools
This library provides helper tools used by the JavaScript logger.
Tools
Queue<T>
Generic FIFO queue. Used by makeThrottle
to store pipeline functions to be executed as concurrent 'slots' become available. Provides fast retrieval for any primitive or object that needs ordered, first-in, first-out retrieval.
Used to store .log()
Promises that are being batched/throttled.
Usage example
import { Queue } from "@logtail/tools";
interface IPerson {
name: string;
age: number;
}
const q = new Queue<IPerson>();
q.push({ name: "Jeff", age: 50 });
q.push({ name: "Sally", age: 39 });
while (q.length) {
console.log(q.shift().name);
}
makeThrottle<T>(max: number)
Returns a throttle
higher-order function, which wraps an async
function, and limits the number of active Promises to max: number
The throttle
function has this signature:
throttle(fn: T): (...args: InferArgs<T>[]) => Promise<InferArgs<T>>
Usage example
import Logtail from "@logtail/logger";
import { makeThrottle } from "@logtail/tools";
const logtail = new Logtail("sourceToken");
const throttle = makeThrottle(2);
const pipeline = async (log) =>
new Promise((resolve) => {
setTimeout(() => resolve(log), 2000);
});
logtail.addPipeline(throttle(pipeline));
const promises = [];
for (let i = 0; i < 10; i++) {
promises.push(logtail.log({ message: `Hello ${i}` }));
}
void (async () => {
void (await promises);
})();
makeBatch(size: number, flushTimeout: number)
Creates a higher-order batch function aggregates Logtail logs and resolves when either size
# of logs have been collected, or when flushTimeout
(in ms) has elapsed -- whichever occurs first.
This is used alongside the throttler to provide an array of ILogtailLog
to the function set in the .setSync()
method, to be synced with Better Stack
Used internally by the @logtail/core Base class
to implicitly batch logs:
const throttle = makeThrottle(this._options.syncMax);
const throttler = throttle((logs: any) => {
return this._sync!(logs);
});
const batcher = makeBatch(this._options.batchSize, this._options.batchInterval);
this._batch = batcher((logs: any) => {
return throttler(logs);
});
LICENSE
ISC